//
//  剑指Offer22. 链表中倒数第k个节点.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/25.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class SolutionSword22 {
    // 链表中倒数第k个节点
    // 采用双指针法
    func getKthFromEnd(_ head: ListNode?, _ k: Int) -> ListNode? {
        var slow = head
        var fast = head
        var m = k
        while fast != nil {
            if m <= 0 {
                slow = slow?.next
            }
            m -= 1
            fast = fast?.next
        }
        return slow
    }

    static func test(){
        let node1 = ListNode(1)
        let node2 = ListNode(2)
        let node3 = ListNode(3)
        let node4 = ListNode(4)
        let node5 = ListNode(5)
        node1.next = node2
        node2.next = node3
        node3.next = node4
        node4.next = node5
        let solution = SolutionSword22()
        let result = solution.getKthFromEnd(node1, 2)
        print(result)
    }
}
